package com.luoyuanxiangvip.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.luoyuanxiangvip.common.constant.Constant;
import com.luoyuanxiangvip.common.enums.ConfigEnum;
import com.luoyuanxiangvip.common.utils.AjaxResult;
import com.luoyuanxiangvip.common.utils.RestClientUtil;
import com.luoyuanxiangvip.common.vo.OtherOption;
import com.luoyuanxiangvip.core.service.IBizLogsService;
import com.luoyuanxiangvip.core.service.IConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Map;

/**
 * <p>
 * 前端api
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/5/28
 */
@RestController
@Api(description = "前台api管理")
@Slf4j
public class IndexController {

    @Resource
    @Lazy
    private IConfigService iConfigService;
    @Resource
    @Lazy
    private IBizLogsService iBizLogsService;

    @PostMapping("/logs")
    @ApiOperation(value = "记录日志信息")
    public AjaxResult logs(@RequestBody Map<String, Object> us) {
        String agent = (String) us.get("agent");
        Boolean aBoolean = iBizLogsService.saveLogs(agent);
        return aBoolean ? AjaxResult.success() : AjaxResult.error();
    }

    @GetMapping("/auth/userInfo")
    @ApiOperation(value = "获取博主信息")
    public AjaxResult index() {
        return AjaxResult.success("获取博主信息成功", iConfigService.getAdminUserInfo());
    }

    @GetMapping("/option")
    @ApiOperation(value = "获取设置")
    public AjaxResult option() {
        return AjaxResult.success("获取设置成功", iConfigService.getOption());
    }

    @GetMapping("/expansion/gitee")
    @ApiOperation(value = "获取仓库")
    public AjaxResult projects() {
        OtherOption otherOption = iConfigService.getValue(ConfigEnum.OTHER_OPTION.getKey());
        String url = MessageFormat.format(Constant.GITEE_URL, otherOption.getGiteeName(), otherOption.getGiteeAuth());
        String s = RestClientUtil.get(url, "UTF-8");
        return AjaxResult.success("获取仓库成功", JSONArray.parseArray(s));
    }

}
